//
//  ARWorkWaterFlowController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/21.
//

import UIKit
import CPFWaterfallFlowLayout
import SnapKit
import MJRefresh

/// 瀑布流
class ARWorkWaterFlowController: ARBaseViewController {

    // MARK: - Property
    
    let viewModel: ARWorkWaterFlowViewModelProvider
    var shouldHideMoreBtnWhenWorkAuthorIsCurrentUser = true
    
    /// cell.height与cell.width 系数数组
    /// - note:
    /// 这里是瀑布流cell高度的比例随机，cell.height = cell.width * ratio，如果要都一样，那么数组只传入一个值即可
    var waterFlowHeightRatio: [Double] = Array(stride(from: 1.0, through: 1.5, by: 0.1))
    private static let cellReuseId = "ar.workwaterflowVc.cellreuseid"
    
    // MARK: - Init
    
    init(viewModel: ARWorkWaterFlowViewModelProvider) {
        self.viewModel = viewModel
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - LifeCycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onWorkLikeChangeNotificationHandler(_:)), name: .workLikeChange, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(onBlackListChangeNotificationHandler(_:)), name: .blackListChange, object: nil)
    }
    
    // MARK: -
    
    private func setupUI() {
        self.view.addSubview(collectionView)
        
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    @objc func loadData() {
        if self.refreshHeader.isRefreshing == false {
            self.ar.showLoading()
        }
        viewModel.loadData { [weak self] err in
            self?.ar.hideHUD()
            self?.refreshHeader.endRefreshing()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            self?.collectionView.reloadData()
        }
    }
    
    func setupHeaderRefresherEnable(_ enable: Bool) {
        if enable {
            self.collectionView.mj_header = self.refreshHeader
        } else {
            self.collectionView.mj_header = nil
        }
    }
    
    @objc private func onWorkLikeChangeNotificationHandler(_ noti: Notification) {
        guard let work = noti.userInfo?["work"] as? ARWorkModel, let index = self.viewModel.dataSource.firstIndex(where: { $0.id == work.id}) else {
            return
        }
        
        collectionView.reloadItems(at: [.init(item: index, section: 0)])
    }
    
    @objc private func onBlackListChangeNotificationHandler(_ noti: Notification) {
        // 直接刷新
        self.loadData()
    }
    
    // MARK: - Lazy
    
    private lazy var collectionView: UICollectionView = {
        
        // layout继承自UICollectionViewFlowLayout，属性配置相同
        let layout = WaterfallLayout()
        layout.minimumLineSpacing = 10
        layout.minimumInteritemSpacing = 13
        layout.sectionInset = UIEdgeInsets(top: 16, left: 16, bottom: 16, right: 16)
        layout.scrollDirection = .vertical

        // 可指定全局列数, delegate方法返回的列数优先
        layout.columnCount = 2
        // cell最小高度
        layout.minHeight = 200
        // cell最大高度，默认为屏幕高度
        layout.maxHeight = 300
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ARWorkCollectionViewCell.self, forCellWithReuseIdentifier: Self.cellReuseId)
        
        collectionView.backgroundColor = .clear
        return collectionView
    }()
    
    private lazy var refreshHeader: ARRefreshHeader = {
        let header = ARRefreshHeader(refreshingTarget: self, refreshingAction: #selector(loadData))
        header.stateLabel?.isHidden = true
        header.lastUpdatedTimeLabel?.isHidden = true
        return header
    }()
}

extension ARWorkWaterFlowController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.viewModel.dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Self.cellReuseId, for: indexPath) as! ARWorkCollectionViewCell
        cell.shouldHideMoreBtnWhenWorkAuthorIsCurrentUser = self.shouldHideMoreBtnWhenWorkAuthorIsCurrentUser
        if indexPath.item < self.viewModel.dataSource.count {
            let model = self.viewModel.dataSource[indexPath.item]
            cell.updateModel(model, moreActionType: self.viewModel.cellMoreActionType)
        }
        cell.delegate = self
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        // 因为这里封面大小都一样，不能体现瀑布流，所以就做一个随机的高度
        let numbers = self.waterFlowHeightRatio
        let randomIndex = Int.random(in: 0..<numbers.count)
        let randomNumber = numbers[randomIndex]
        return .init(width: 1, height: 1 * randomNumber)
        /*
        if indexPath.item < self.viewModel.dataSource.count {
            let model = self.viewModel.dataSource[indexPath.item]
            if let path = model.realPicCover(),
               let image = ARWorkModel.localImageFor(path) {
                return image.size
            }
        }
        return .init(width: 100, height: 100)
         */
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        if indexPath.item < self.viewModel.dataSource.count {
            let model = self.viewModel.dataSource[indexPath.item]
            let vc = ARDiscoverWorkDetailController(workId: model.id)
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
}

extension ARWorkWaterFlowController: ARWorkCollectionViewCellDelegate {
    
    func workCollectionViewCellClickedLikeBtn(_ cell: ARWorkCollectionViewCell) {
        guard let model = cell.model else {
            return
        }
        self.viewModel.likeOrUnLikeWork(model) { [weak self] err in
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            
            // 成功 - 更新cell
            cell.updateModel(model, moreActionType: self?.viewModel.cellMoreActionType ?? .more)
        }
    }
    
    func workCollectionViewCellClickedAvatarBtn(_ cell: ARWorkCollectionViewCell) {
        guard let userid = cell.model?.authorId else {
            return
        }
        
        self.navigationController?.pushViewController(ARPersonalPageController(userId: userid), animated: true)
    }
    
    func workCollectionViewCellClickedMoreBtn(_ cell: ARWorkCollectionViewCell, type: ARWorkCollectionViewCell.MoreActionType) {
        
        guard let model = cell.model else {
            return
        }
        
        switch type {
        case .more:
            if let user = model.author {
                ARUserRelationshipHelper.workMoreAction(user: user, vc: self) { [weak self] type, err in
                    if let err = err {
                        self?.ar.makeToast(err.localizedDescription)
                        return
                    }
                    switch type {
                    case .blackList: break
                        // 黑名单 - 重新拉取
//                        self?.loadData()
                    case .follow:
                        // 成功 - 更新cell
                        cell.updateModel(model, moreActionType: self?.viewModel.cellMoreActionType ?? .more)
                    }
                }
            }
        case .delete:
            self.ar.showLoading()
            self.viewModel.deleteWork(model) { [weak self] err in
                self?.ar.hideHUD()
                if let err = err {
                    self?.ar.makeToast(err.localizedDescription)
                    return
                }
                
                // 刷新一下
                self?.collectionView.reloadData()
            }
        }
        
    }
    
}
